package com.jt.common.filter;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

//过滤器
interface Filter{
    boolean invoke();
}
//控制器
interface Servlet{
    void dispatch();
}

//过滤链
class FilterChain{
    private List<Filter> filters = new CopyOnWriteArrayList<>();
    private Servlet servlet;

    public FilterChain(List<Filter> filters, Servlet servlet) {
        this.filters.addAll(filters);
        this.servlet = servlet;
    }

    public void doFilter(){
        for (int i = 0; i < filters.size(); i++) {
            if (!filters.get(i).invoke()) return;
         }
        servlet.dispatch();//请求分发
    }
}

public class FilterChainTests {
    public static void main(String[] args) {
        Filter filter1 = new Filter() {
            @Override
            public boolean invoke() {
                System.out.println("filter1");
                return true;
            }
        };
        Filter filter2 = new Filter() {
            @Override
            public boolean invoke() {
                System.out.println("filter2");
                return true;
            }
        };

        Servlet servlet = new Servlet() {
            @Override
            public void dispatch() {
                System.out.println("将任务分发出来");
            }
        };

        List<Filter> filters = new CopyOnWriteArrayList<>();
        filters.add(filter1);
        filters.add(filter2);

        FilterChain fc = new FilterChain(filters,servlet);
        fc.doFilter();
    }
}
